
package com.huizhan.web.controller;

import org.springframework.web.bind.annotation.*;
import org.reflections.vfs.Vfs.Dir;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.domain.Sort.*;
import io.swagger.annotations.*;
import java.util.*;

import javax.servlet.http.HttpServletRequest;

import com.huizhan.web.view.*;
import com.huizhan.web.dao.*;
import com.huizhan.web.model.*;

/**
 * 展商api
 */
 
@Api(tags = "Exhibitor",description = "展商")
@RestController
public class ExhibitorController {
    
    @Autowired
    private ExhibitorDao dao;
   
    @Autowired
    private ProjectDao pdao;

    @Autowired
    private DocumentTypeDao ddao;

    @Autowired
    private DistributeDao Ddao;
   
    @Autowired
    private DocumentRecordDao recordDao;
    
    /**
     * 获取展商集合
     * @return api结果
     */
    @ApiOperation(value = "获取展商集合")
    @RequestMapping(value =  "/api/Exhibitor/",method = {RequestMethod.GET})
    public ApiResult<List<Exhibitor>> Get(){
         ApiResult<List<Exhibitor>> result=new ApiResult<List<Exhibitor>>();
        try 
        {
            List<Exhibitor> res = dao.findAll();
            result.setData(res);
        }catch(Exception e){
            result.setHasError(true);
            result.setMessage(e.getMessage());
        }
        return  result;
    }

    /**
     * 批量新增证件信息
     * @param id 证件类型ID
     * @param list 证件信息
     * @return api结果
     */
    @ApiOperation(value = "批量新增证件信息")
    @RequestMapping(value =  "/api/Exhibitor/AddList/{id}",method = {RequestMethod.PUT})
    public ApiResult<Exhibitor> AddList(@PathVariable String id,@RequestBody List<Exhibitor> list, HttpServletRequest request){
        ApiResult<Exhibitor> result=new ApiResult<Exhibitor>();
        try
        { 
            List<Exhibitor> exhibitors=dao.findByProjectId(id);
            List<Exhibitor> list2=new ArrayList<Exhibitor>();
            DocumentType type = isAddExhibitor(id);
            Project project=pdao.getOne(id);

            for (Exhibitor exhibitor : list) {
                exhibitor.setProjectId(id);
                exhibitor.setCreateDate(new Date());
                
                exhibitors.forEach(a->{
                    if(a.getPhone().equals(exhibitor.getPhone())){
                        list2.add(exhibitor);
                        return;
                    }
                });
            }

            list.removeAll(list2);

            if(list.size()>0){

                list.forEach(model->{

                    Distribute distribute = Ddao.findByDocumentTypeIdAndPhone(type.getDocumentTypeId(),model.getPhone());

                    if(distribute==null){   
                        distribute=new Distribute();
                        distribute.setDocumentTypeId(type.getDocumentTypeId());
                        distribute.setName(model.getName());
                        distribute.setProjectId(project.getProjectId());
                        distribute.setParentId(0L);
                        distribute.setPhone(model.getPhone());
                        distribute.setCreateDate(new Date());
                        distribute.setTypeName(type.getName());
                        distribute.setTotal(model.getPersonal());
                        distribute.setUseNumber(0L);
                        distribute.setLevel(0L);
        
                        Ddao.save(distribute);
    
                        DocumentRecord record=new DocumentRecord();
                        record.setDistributeId(distribute.getDistributeId());
                        record.setTypeName(type.getName());
                        record.setCreateDate(new Date());
                        record.setProjectId(type.getProjectId());
                        record.setDocumentTypeId(type.getDocumentTypeId());
                        record.setUrl("系统给"+model.getPhone()+"("+model.getName()+")"+distribute.getTotal()+"张证件");
                        record.setPhone(model.getPhone());
                        record.setName(model.getName());
                        record.setNumber(distribute.getTotal());                    
                        recordDao.save(record);
                        SendSMS(project,distribute,distribute.getTotal(), request);
                    }else if(!distribute.getTotal().equals(model.getPersonal())){
                        if(distribute.getTotal()<model.getPersonal()){
                            SendSMS(project, distribute,model.getPersonal()-distribute.getTotal(),request);
                        }
                        distribute.setTotal(model.getPersonal());
                        Ddao.save(distribute);
                        
                        DocumentRecord record=new DocumentRecord();
                        record.setDistributeId(distribute.getDistributeId());
                        record.setTypeName(type.getName());
                        record.setCreateDate(new Date());
                        record.setProjectId(type.getProjectId());
                        record.setDocumentTypeId(type.getDocumentTypeId());
                        record.setUrl("系统给"+model.getPhone()+"("+distribute.getName()+")"+(model.getPersonal()-distribute.getTotal())+"张证件");
                        record.setPhone(model.getPhone());
                        record.setName(model.getName());
                        record.setNumber(model.getPersonal()-distribute.getTotal());            
                        recordDao.save(record);
                        dao.save(model);
                    }
                });

                dao.saveAll(list);
            }

            result.setTotal(Long.parseLong(String.valueOf(list.size())));
            result.setMessage("导入成功:"+list.size()+"条,未导入相同手机:"+list2.size());            
        }catch(Exception e){
            result.setHasError(true);
            result.setMessage(e.getMessage());
        }
        return  result;
    }

    /**
     * 根据项目ID获取展商集合
     * @param id 项目办证/门禁点ID
     * @return api结果
     */
    @ApiOperation(value = "根据项目ID获取展商集合")
    @RequestMapping(value =  "/api/Exhibitor/Project/{projectId}",method = {RequestMethod.GET})
    public ApiResult<List<Exhibitor>> Project(@PathVariable String projectId){
        ApiResult<List<Exhibitor>> result=new ApiResult<List<Exhibitor>>();
        try
        {
            List<Exhibitor> model= dao.findByProjectId(projectId);
            result.setData(model);
        }catch(Exception e){
            result.setHasError(true);
            result.setMessage(e.getMessage());
        }
        return  result;
    }

    /**
     * 根据ID获取展商信息
     * @param id 展商ID
     * @return api结果
     */
    @ApiOperation(value = "根据ID获取展商信息")
    @RequestMapping(value =  "/api/Exhibitor/{id}",method = {RequestMethod.GET})
    public ApiResult<Exhibitor> Get(@PathVariable Long id){
        ApiResult<Exhibitor> result=new ApiResult<Exhibitor>();
        try
        {
            Exhibitor model= dao.getOne(id);
            result.setData(model);
        }catch(Exception e){
            result.setHasError(true);
            result.setMessage(e.getMessage());
        }
        return  result;
    }

    /**
     * 修改展商信息
     * @param id 展商ID
     * @param model 展商信息
     * @return api结果
     */
    @ApiOperation(value = "修改展商信息")
    @RequestMapping(value =  "/api/Exhibitor/{id}",method = {RequestMethod.PUT})
    public ApiResult<Exhibitor> Edit(@PathVariable Long id,@RequestBody Exhibitor model, HttpServletRequest request){
        ApiResult<Exhibitor> result=new ApiResult<Exhibitor>();
        try
        {
            Exhibitor exhibitor=dao.findByProjectIdAndPhone(model.getProjectId(),model.getPhone());

            if(exhibitor==null){
                result.setHasError(true);
                result.setMessage("手机号码不能更改");
            }else{
                DocumentType type = isAddExhibitor(model.getProjectId());
                Project project=pdao.getOne(model.getProjectId());
                Distribute distribute = Ddao.findByDocumentTypeIdAndPhone(type.getDocumentTypeId(),model.getPhone());

                if(distribute==null){   
                    distribute=new Distribute();
                    distribute.setDocumentTypeId(type.getDocumentTypeId());
                    distribute.setName(model.getName());
                    distribute.setProjectId(project.getProjectId());
                    distribute.setParentId(0L);
                    distribute.setPhone(model.getPhone());
                    distribute.setCreateDate(new Date());
                    distribute.setTypeName(type.getName());
                    distribute.setUseNumber(0L);
                    distribute.setTotal(model.getPersonal());
                    distribute.setLevel(0L);
    
                    Ddao.save(distribute);

                    DocumentRecord record=new DocumentRecord();
                    record.setDistributeId(distribute.getDistributeId());
                    record.setTypeName(type.getName());
                    record.setCreateDate(new Date());
                    record.setProjectId(type.getProjectId());
                    record.setDocumentTypeId(type.getDocumentTypeId());
                    record.setUrl("系统给"+model.getPhone()+"("+model.getName()+")"+distribute.getTotal()+"张证件");
                    record.setPhone(model.getPhone());
                    record.setName(model.getName());
                    record.setNumber(distribute.getTotal());                    
                    recordDao.save(record);
                    SendSMS(project,distribute,distribute.getTotal(), request);
                }else if(!distribute.getTotal().equals(model.getPersonal())){
                    if(distribute.getTotal()<model.getPersonal()){
                        SendSMS(project, distribute,model.getPersonal()-distribute.getTotal(),request);
                    }
                    distribute.setTotal(model.getPersonal());
                    Ddao.save(distribute);
                    
                    DocumentRecord record=new DocumentRecord();
                    record.setDistributeId(distribute.getDistributeId());
                    record.setTypeName(type.getName());
                    record.setCreateDate(new Date());
                    record.setProjectId(type.getProjectId());
                    record.setDocumentTypeId(type.getDocumentTypeId());
                    record.setUrl("系统给"+model.getPhone()+"("+distribute.getName()+")"+(model.getPersonal()-distribute.getTotal())+"张证件");
                    record.setPhone(model.getPhone());
                    record.setName(model.getName());
                    record.setNumber(model.getPersonal()-distribute.getTotal());            
                    recordDao.save(record);
                    dao.save(model);
                }
                model.setExhibitorId(id);
                model.setProjectId(exhibitor.getProjectId());
                model.setCreateDate(exhibitor.getCreateDate());
                dao.save(model);
                result.setData(model);
            }
        }catch(Exception e){
            result.setHasError(true);
            result.setMessage(e.getMessage());
        }
        return  result;
    }

    /**
     * 添加展商信息
     * @param model 展商信息
     * @return api结果
     */
    @ApiOperation(value = "添加展商信息")
    @RequestMapping(value =  "/api/Exhibitor/",method = {RequestMethod.POST})
    public ApiResult<Exhibitor> Add(@RequestBody Exhibitor model, HttpServletRequest request){
        ApiResult<Exhibitor> result=new ApiResult<Exhibitor>();
        try
        {
            if(model.getProjectId()==null||model.getProjectId().length()==0){
                result.setHasError(true);
                result.setMessage("项目ID不能为空");
            }else if(model.getPhone()==null||model.getPhone().length()==0){
                result.setHasError(true);
                result.setMessage("手机不能为空");
            }else if(dao.findByProjectIdAndPhone(model.getProjectId(),model.getPhone())!=null){
                result.setHasError(true);
                result.setMessage("项目ID不能为空");
            } else if(model.getPersonal()<=0){
                result.setHasError(true);
                result.setMessage("人数必须大于0");
            }  else{
                DocumentType type = isAddExhibitor(model.getProjectId());
                Project project=pdao.getOne(model.getProjectId());
                Distribute distribute = Ddao.findByDocumentTypeIdAndPhone(type.getDocumentTypeId(),model.getPhone());

                if(distribute==null){   
                    distribute=new Distribute();
                    distribute.setDocumentTypeId(type.getDocumentTypeId());
                    distribute.setName(model.getName());
                    distribute.setProjectId(project.getProjectId());
                    distribute.setParentId(0L);
                    distribute.setPhone(model.getPhone());
                    distribute.setCreateDate(new Date());
                    distribute.setTypeName(type.getName());
                    distribute.setLevel(0L);
                    distribute.setUseNumber(0L);
                    distribute.setTotal(model.getPersonal());
    
                    Ddao.save(distribute);

                    DocumentRecord record=new DocumentRecord();
                    record.setDistributeId(distribute.getDistributeId());
                    record.setTypeName(type.getName());
                    record.setCreateDate(new Date());
                    record.setProjectId(type.getProjectId());
                    record.setDocumentTypeId(type.getDocumentTypeId());
                    record.setUrl("系统给"+model.getPhone()+"("+model.getName()+")"+distribute.getTotal()+"张证件");
                    record.setPhone(model.getPhone());
                    record.setName(model.getName());
                    record.setNumber(distribute.getTotal());                    
                    recordDao.save(record);
                    SendSMS(project,distribute,distribute.getTotal(), request);
                }else if(!distribute.getTotal().equals(model.getPersonal())){
                    if(distribute.getTotal()<model.getPersonal()){
                        SendSMS(project, distribute,model.getPersonal()-distribute.getTotal(),request);
                    }
                    distribute.setTotal(model.getPersonal());
                    Ddao.save(distribute);
                    
                    DocumentRecord record=new DocumentRecord();
                    record.setDistributeId(distribute.getDistributeId());
                    record.setTypeName(type.getName());
                    record.setCreateDate(new Date());
                    record.setProjectId(type.getProjectId());
                    record.setDocumentTypeId(type.getDocumentTypeId());
                    record.setUrl("系统给"+model.getPhone()+"("+distribute.getName()+")"+(model.getPersonal()-distribute.getTotal())+"张证件");
                    record.setPhone(model.getPhone());
                    record.setName(model.getName());
                    record.setNumber(model.getPersonal()-distribute.getTotal());            
                    recordDao.save(record);
                    dao.save(model);
                }

                model.setCreateDate(new Date());
                
                dao.save(model);

                result.setData(model);
            }
        }catch(Exception e){
            result.setHasError(true);
            result.setMessage(e.getMessage());
        }
        return result;
    }
    
    private Boolean SendSMS(Project project,Distribute model,Long count, HttpServletRequest request){

        boolean b=false;

        try {
            String data="{\"account\":\"dh81653\",\"password\":\""+
            TenpayUtil.MD5("e3YiG73c").toLowerCase()
            +"\",\"msgid\":\""
            +(UUID.randomUUID().toString())
            +"\",\"phones\":"
            +model.getPhone()
            +",\"content\":\""
            +model.getName()
            +"您收到"
            +project.getName()
            +"电子证件"
            +(count)
            +"张 ";

            /*if(model.getTotal()==count&&count<6){
                for (Document Document : list) {
                    data+=request.getScheme() + "://" + request.getServerName()+"/"+Document.getDocumentTypeId()+","+Document.getCode()+"\\n";
                }
            }else{*/
                data+=request.getScheme() + "://" + request.getServerName()+"/d/"+model.getDistributeId();
            //}

            data+="\",\"sign\":\"【"
            +project.getSignName()
            +"】\",\"subcode\":\"\",\"sendtime\":\"\"}";

            TenpayHttpClient httpClient = new TenpayHttpClient();  

            httpClient.callHttpPost("http://www.dh3t.com/json/sms/Submit", data);
            String  resContent = httpClient.getResContent();

            if(resContent.contains("提交成功")){
                b=true;
            }
        } catch (Exception e) {
             b=false;
        }
       return b;
    }
    

    private DocumentType isAddExhibitor(String projectId){

        DocumentType type=ddao.findByProjectIdAndName(projectId,"展商");

        if(type==null){
            type = new DocumentType();
            type.setCreateDate(new Date());
            type.setName("展商");
            type.setProjectId(projectId);

            ddao.save(type);
        }

        return type;
    }

    /**
     * 删除展商信息
     * @param id 展商ID
     * @return api结果
     */
    @ApiOperation(value = "删除展商信息")
    @RequestMapping(value =  "/api/Exhibitor/{id}",method = {RequestMethod.DELETE})
    public ApiResult<Object> Delete(@PathVariable  Long id){
        ApiResult<Object> result=new ApiResult<Object>();
        try 
        {
            dao.deleteById(id);
        }catch(Exception e){
            result.setHasError(true);
            result.setMessage(e.getMessage());
        }
        return result;
    }
    
    /**
     * 查询展商分页
     * @param model 账号信息
     * @return api结果
     */
    @ApiOperation(value = "查询展商分页")
    @RequestMapping(value =  "/api/Exhibitor/Search",method = {RequestMethod.POST})
    public ApiResult<List<Exhibitor>> Search(@RequestBody PageExhibitor model){
         ApiResult<List<Exhibitor>> result=new ApiResult<List<Exhibitor>>();
         
        try
        {
            //long time1 = model.getStartDate()!=null?model.getStartDate().getTime()/1000:0;
            //long time2 = model.getEndDate()!=null?model.getEndDate().getTime()/1000:0;
            PageRequest pageable = PageRequest.of(model.getPageIndex(),model.getPageSize(),Direction.DESC,"Exhibitor_Id") ;            
            Page<Exhibitor> page = dao.findByWhere(model.getName(),model.getPhone(),model.getProjectId(),model.getBooth(),model.getState(),pageable);
            result.setData(page.getContent());
            result.setTotal(page.getTotalElements());
        }catch(Exception e){
            result.setHasError(true);
            result.setMessage(e.getMessage());
        }
        return result;
    }
}

